<template>
  <div class="forget-form">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" :title="$t('login.form.forgetPassword')">
        <a-form
          ref="forgetRef"
          :model="forgetForm"
          layout="vertical"
          @submit="handleSubmit"
        >
          <a-form-item
            field="phone"
            :rules="[
              { required: true, message: $t('login.form.telRequired') },
              {
                match: /^1[3456789]\d{9}$/,
                message: $t('login.form.telInvalid'),
              },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="forgetForm.phone"
              :placeholder="$t('login.form.telPlaceholder')"
              :maxlegth="11"
            >
              <template #prefix>
                <icon-mobile />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            field="captcha"
            :rules="[
              { required: true, message: $t('login.form.captchaRequired') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="forgetForm.captcha"
              :placeholder="$t('login.form.captchaPlaceholder')"
              :maxlegth="50"
            >
              <template #prefix>
                <icon-safe />
              </template>
              <template #append>
                <a-button
                  type="text"
                  :loading="smsLoading"
                  @click="getSMSCaptcha"
                >
                  <span v-if="countDown === -2" class="captcha-word">{{
                    $t('login.form.getCaptcha')
                  }}</span>
                  <span v-else-if="countDown === -1" class="captcha-word">{{
                    $t('login.form.regainCaptcha')
                  }}</span>
                  <span v-else class="captcha-word">{{ `${countDown}s` }}</span>
                </a-button>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            field="pwd"
            :rules="[
              { required: true, message: $t('login.form.password.errMsg') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input-password
              v-model="forgetForm.pwd"
              :placeholder="$t('login.form.newPassword')"
              allow-clear
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item
            field="confirmpwd"
            :rules="[
              { required: true, message: $t('login.form.password.errMsg') },
            ]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input-password
              v-model="forgetForm.confirmpwd"
              :placeholder="$t('login.form.confirmPassword')"
              allow-clear
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <div class="option-box">
            <a-button type="primary" html-type="submit" :loading="loading">{{
              $t('login.form.enterConfirm')
            }}</a-button>
            <a-link @click="changeLogin(LoginMethods.password)">{{
              $t('login.form.backLogin')
            }}</a-link>
          </div>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { useI18n } from 'vue-i18n';
  import { getSms, editPassword } from '@/api/user';
  import pwdEncrypt from '@/utils/encryption/pwd';
  import LoginMethods from '../constant';

  const { t } = useI18n();

  const forgetForm = reactive({
    phone: '',
    captcha: '',
    pwd: '',
    confirmpwd: '',
  });

  // 处理验证码
  const countDown = ref(-2);
  const smsLoading = ref(false);
  const forgetRef = ref<FormInstance>();
  // 存储验证码
  let captchaKey = '';
  const getSMSCaptcha = async () => {
    if (countDown.value >= 0) {
      Message.warning(t('login.form.captchaHoldOn'));
      return;
    }
    const res = await forgetRef.value?.validateField('phone');
    // 仅判断手机号是否校验通过
    if (res) {
      return;
    }
    smsLoading.value = true;
    try {
      const { data } = await getSms(forgetForm.phone);
      captchaKey = data;
    } catch (err) {
      // you can report use errorHandler or other
      if (typeof err === 'string') {
        Message.error(err);
      }
    } finally {
      smsLoading.value = false;
      updataCountDown();
    }
  };

  const updataCountDown = () => {
    countDown.value = 60;
    const counter = setInterval(() => {
      if (countDown.value === 0) {
        clearInterval(counter);
        countDown.value = -1;
      } else {
        countDown.value--;
      }
    }, 1000);
  };

  const { loading, setLoading } = useLoading();
  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      if (forgetForm.confirmpwd !== forgetForm.pwd) {
        Message.error(t('login.form.confirmpwd.errMsg'));
        return;
      }
      setLoading(true);
      try {
        const { captcha, phone, pwd } = values;
        const data = {
          captcha,
          phone,
          key: captchaKey,
          pwd: pwdEncrypt(pwd),
        };
        const res = await editPassword(data);
        Message.success(t('login.form.resetPwd.success'));
      } catch (err) {
        Message.error((err as Error).message);
      } finally {
        setLoading(false);
      }
    }
  };

  const emit = defineEmits(['changeLogin']);
  const changeLogin = (method: LoginMethods) => {
    emit('changeLogin', method);
  };
</script>

<script lang="ts">
  export default {
    name: 'ForgetForm',
  };
</script>

<style lang="less" scoped>
  .option-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
